/**
 * Created by yiihua-013 on 16/10/27.
 *
 * 一致性hash
 */

'use strict';

const util = require('util')

var Hash = require('./hash')

function ConsistentHash() {
    this.positions = {}; // key:虚拟节点的hash,value:虚拟节点名
}

util.inherits(ConsistentHash, Hash)

var fn = ConsistentHash.prototype;

fn.MUL    = 64; // 一个真实节点对应64个虚拟节点
fn.lookup = function (key) {
    var point = this.hash(key); // 算出key的落点
    var objKeys = Object.keys(this.positions);
    var pos = objKeys[0];
    var node = this.positions[pos]; // 初始化为圆环上的第一个点
    for (let hash of objKeys) {
        if (point <= hash) {
            node = this.positions[hash];
            break;
        }
    }
    return node;
};

/**
 * 添加一个物理节点相当于添加64个虚拟节点
 * @param node
 */
fn.addNode = function (node) {
    for (var i = 0; i < this.MUL; i++) {
        let vNodeName = `v_node_${node}_${i}`;
        let hash      = this.hash(vNodeName);
        if (this.positions[hash]) continue;
        this.positions[hash] = node;
    }
};

fn.deleteNode = function (node) {
    for (var hash in this.positions) {
        if (this.positions[hash] == node) delete this.positions[hash];
    }
};

module.exports = ConsistentHash;

// var hash = new ConsistentHash();
// hash.addNode('192.168.1.1')
// hash.addNode('192.168.1.1')
// hash.addNode('192.168.1.2')
// hash.addNode('192.168.1.3')
//
// hash.deleteNode('192.168.1.3')
//
// var key = 'name';
// console.log(`key ${key}的落点为${hash.hash(key)},所在服务器为:${hash.lookup(key)}`)
// key = "sex";
// console.log(`key ${key}的落点为${hash.hash(key)},所在服务器为:${hash.lookup(key)}`)
